<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace app\common\model\platform;

use app\common\model\addon\Addons;
use app\common\model\BaseModel;

/**
 * 小程序模型
 * @package app\common\model
 * User: liuhongbin
 * Date: 2021-05-25 14:16
 */
class PlatformApp extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'platform_app';

    protected $type = array(
        'config'        => 'json',
        'server_config' => 'json',
        'other_data'    => 'json',
        'setting'       => 'json'
    );

    /**
     * 获取平台应用小程序配置
     * @param string $addon_name
     * @param int $plaid
     * @return array|mixed
     */
    public function getPlatformAppConfig($addon_name = '', $appid = 0)
    {
        $appid = $appid ?: get_appid();
        $addon_name = $addon_name ?: get_addon();
        $res = $this->where(['id' => $appid, 'addon_name' => $addon_name])->field('config')->findOrEmpty();
        return $res->config ?? [];
    }

    /**
     * 获取平台详情
     * @param $plaid
     * @return PlatformWxapp|array|mixed|\think\Model|null
     */
    public function getPlatformDetails($plaid)
    {
        $SettingModel = new PlatformSetting();
        $res = $this->where(['plaid' => $plaid])->find();
        $res['api_url'] = url("h5/api/index", ['p' => $plaid], true, true)->build();
        $res['setting'] = array(
            'pay'      => $SettingModel->where(['key' => 'pay', 'plaid' => $plaid])->find(),
            'transfer' => $SettingModel->where(['key' => 'transfer', 'plaid' => $plaid])->find()
        );
        return $res;
    }

    public function getAddonAttr($value, $data)
    {
        $res = (new Addons())->where('name', $data['addon_name'])->append(['default_url'])->find();
        if ($res) {
            $res = $res->toArray();
            $res['default_url'] = str_replace('plaid=0', 'plaid=' . $data['plaid'], $res['default_url']) . "&appid=" . $data['id'];
            return $res;
        } else {
            return false;
        }
    }

    public function searchAddonAttr($query, $value, $data)
    {
        $addon_names = [];
        $addons = (new Addons())->where('status', 1)->field('name')->select()->toArray();
        foreach ($addons as $key => $value) {
            $addon_names[] = $value['name'];
        }
        $query->where('addon_name', 'in', $addon_names);
    }
}
